import os
import sys
import logging
import pygame

try:
    __file__
except NameError as e:
    from whereis import mymain
    rootdir = mymain()
else:
    rootdir = os.path.dirname(os.path.dirname(__file__))

sys.path.insert(0, rootdir)
from lib.bashlog import getlogger
from lib.tracemore import get_exc_plus
from lib.config import Config
from lib.runline import RunLine
from lib.topic import Topic
from lib.sprite import Group
from lib import color
from lib import tool
from lib import events
sys.path.pop(0)

logger = logging.getLogger('wordson.gamepage')
cfg = Config()

class GamePage(Group):
    screenx = cfg.screen[0] / 2
    def __init__(self):
        super(GamePage, self).__init__()

        self.runline = RunLine()
        self.topic = Topic()

        self.extend(self.runline, self.topic)

    def update(self, time):
        self.extend(self.runline)
        self.runline.update(time)
        self.topic.update(time)

    def draw(self, surface):
        self.runline.draw(surface)
        self.topic.draw(surface)


    def handle(self, event):
        children = (self.runline, self.topic)
        if any(map(lambda x: x.handle(event), children)):
            return True

    def is_current(self, result):
        if result:
            return self.runline.jump_next()
        return self.runline.roll_next()

    def set(self, title, options=None):
        self.topic.set(title, options=None)
        if not options:    # input
            for each in (self.topic.title.rect, self.topic.inputer.rect):
                each.centerx = self.screenx
                logger.debug(each)

if __name__ == '__main__':
    getlogger(logger, logging.DEBUG)
    getlogger('wordson.topic', logging.DEBUG)
    getlogger('wordson.inputer', logging.DEBUG)

    pygame.init()
    pygame.key.set_repeat(cfg.key_repeat_delay, cfg.key_repeat_interval)
    pygame.display.set_caption(cfg.title)

    screen = pygame.display.set_mode(cfg.screen)

    run = True
    clock = pygame.time.Clock()
    page = GamePage()
    # page.topic.set('Select your favorite Zen of Python:')
    page.set('X:')
#     page.topic.set('Select your favorite Zen of Python:', '''以动手实践为荣 , 以只看不练为耻;
# 以打印日志为荣 , 以单步跟踪为耻;
# 以空格缩进为荣 , 以制表缩进为耻;
# 以单元测试为荣 , 以人工测试为耻;'''.splitlines())

    page.is_current(True)
    page.is_current(False)
    page.is_current(True)
    page.is_current(False)

    while run:
        for event in pygame.event.get():
            if page.handle(event):
                continue
            if event.type == pygame.QUIT:
                run = False

        inter = clock.tick(cfg.tick)
        page.update(inter)
        screen.fill(color.white)
        page.draw(screen)
        pygame.display.flip()

    pygame.quit()
